package com.link.base.base.map.service;

import com.alibaba.fastjson.JSONObject;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.HttpUtils;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class BaiduMapServiceImpl implements BaiduMapService {
    /**
     * 调用地点输入提示服务
     *
     * @param keywords 关键字
     * @author LiQun
     * @date 2019/3/28 23:01
     */
    @Override
    public Map<String, Object> suggestion(String keywords,String location) throws Exception {
        Map<String, Object> resultMap = new HashMap<>(16);
        Map<String, Object> paramsMap = new HashMap<>(16);
        paramsMap.put("query", keywords);
        paramsMap.put("region", "全国");
        paramsMap.put("output", "json");
        paramsMap.put("city_limit", "false");
        paramsMap.put("ak", YmlConstants.getBaiduMapKey());
//        paramsMap.put("ak", "AUe62rP2ggrGatfHHmS6A1nriNmT03VZ");
        if (location != null && !"".equals(location)) {
            paramsMap.put("location", location);
        }
        String url = null;
        try {
            url = "http://api.map.baidu.com/place/v2/suggestion";
            String resultParams = HttpUtils.sendGet(url, toQueryString(paramsMap));
            JSONObject result = JSONObject.parseObject(resultParams);
            if (null == result) {
                throw new BasicServiceException("调用接口异常，请重试");
            } else {
                String success = result.get("status").toString();
                if ("0".equals(success)) {
                    resultMap.put("result", result.get("result"));
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new BasicServiceException(e.getMessage());
        }
        return resultMap;
    }


    private static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            if ("location".equals(pair.getKey())) {
                queryString.append(pair.getValue());
            } else {
                queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8"));
            }
            queryString.append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    public static void main(String[] args) throws Exception {
        BaiduMapServiceImpl baiduMapService = new BaiduMapServiceImpl();
        Map<String, Object> suggestion = baiduMapService.suggestion("上海",null);
        System.out.println(suggestion);
    }
}
